<template>
    <div class="min-h-screen bg-gradient-to-br from-indigo-500 via-purple-500 to-pink-500 flex items-center justify-center p-4">
        <div class="w-full max-w-5xl bg-white bg-opacity-90 rounded-2xl shadow-xl overflow-hidden flex flex-col md:flex-row">
            <!-- 左侧内容 - 移动端隐藏 -->
            <div class="hidden md:flex w-full md:w-1/2 bg-gradient-to-br from-indigo-500 to-purple-600 p-8 flex-col justify-center">
                <div class="flex items-center mb-8">
                    <div class="w-12 h-12 rounded-full bg-white flex items-center justify-center mr-4">
                        <svg class="w-8 h-8 text-indigo-600" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                    <h1 class="text-2xl font-bold text-white">九型人格测试系统</h1>
                </div>

                <div class="text-white">
                    <p class="mb-6 text-indigo-100">九型人格是一种的性格分析工具，它能帮助你深入了解自己的行为模式、思维方式和情感反应。</p>
                    <ul class="space-y-3">
                        <li class="flex items-center">
                            <i class="fa fa-check-circle mr-2 text-green-300"></i>
                            <span>专业的人格类型评估</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-check-circle mr-2 text-green-300"></i>
                            <span>详细的性格分析报告</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-check-circle mr-2 text-green-300"></i>
                            <span>个性化成长建议</span>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 右侧注册表单 - 共用部分 -->
            <div class="w-full md:w-1/2 p-6 md:p-8">
                <!-- 移动端logo - PC端隐藏 -->
                <div class="flex justify-center mb-6 md:hidden">
                    <img src="~assets/image/jiuxin_logo.jpg" class="w-20" />
                </div>

                <h1 class="text-2xl font-bold text-center md:text-left text-gray-800 mb-6">
                    <span class="md:hidden">九型人格测试系统</span>
                    <span class="hidden md:inline">创建账户</span>
                </h1>

                <!-- 注册类型切换 -->
                <div class="mb-6">
                    <div class="flex border-b border-gray-200">
                        <button
                            @click="state.form.registerType = 'mobile'"
                            :class="{ 'text-indigo-600 border-b-2 border-indigo-600': state.form.registerType === 'mobile' }"
                            class="flex-1 py-2 text-center font-medium text-gray-700 focus:outline-none"
                        >
                            手机注册
                        </button>
                        <button
                            @click="state.form.registerType = 'email'"
                            :class="{ 'text-indigo-600 border-b-2 border-indigo-600': state.form.registerType === 'email' }"
                            class="flex-1 py-2 text-center font-medium text-gray-700 focus:outline-none"
                        >
                            邮箱注册
                        </button>
                    </div>
                </div>

                <!-- 表单部分 -->
                <form @submit.prevent="handleSubmit" class="space-y-4">
                    <!-- 用户名、密码、验证码等表单字段保持不变 -->
                    <div>
                        <label for="pc-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                        <input
                            v-model="state.form.username"
                            type="text"
                            id="pc-username"
                            class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition"
                            placeholder="请输入用户名"
                        />
                        <p v-if="errors.username" class="mt-1 text-sm text-red-600">{{ errors.username }}</p>
                    </div>

                    <div>
                        <label for="pc-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input
                            v-model="state.form.password"
                            type="password"
                            id="pc-password"
                            class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition"
                            placeholder="请输入密码"
                        />
                        <p v-if="errors.password" class="mt-1 text-sm text-red-600">{{ errors.password }}</p>
                    </div>

                    <div v-if="state.form.registerType === 'mobile'">
                        <label for="pc-mobile" class="block text-sm font-medium text-gray-700 mb-1">手机号</label>
                        <input
                            v-model="state.form.mobile"
                            type="text"
                            id="pc-mobile"
                            class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition"
                            placeholder="请输入手机号"
                        />
                        <p v-if="errors.mobile" class="mt-1 text-sm text-red-600">{{ errors.mobile }}</p>
                    </div>

                    <div v-if="state.form.registerType === 'email'">
                        <label for="pc-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                        <input
                            v-model="state.form.email"
                            type="email"
                            id="pc-email"
                            class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition"
                            placeholder="请输入邮箱"
                        />
                        <p v-if="errors.email" class="mt-1 text-sm text-red-600">{{ errors.email }}</p>
                    </div>

                    <div>
                        <label for="pc-captcha" class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
                        <div class="flex space-x-2">
                            <input
                                v-model="state.form.captcha"
                                type="text"
                                id="pc-captcha"
                                class="flex-1 px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition"
                                placeholder="请输入验证码"
                            />
                            <button
                                type="button"
                                @click="sendCaptcha"
                                :disabled="state.codeSendCountdown > 0 || state.sendCaptchaLoading"
                                class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition disabled:bg-indigo-300 flex items-center justify-center min-w-[120px]"
                            >
                                <svg
                                    v-if="state.sendCaptchaLoading"
                                    class="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                                    xmlns="http://www.w3.org/2000/svg"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                >
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path
                                        class="opacity-75"
                                        fill="currentColor"
                                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                    ></path>
                                </svg>
                                {{ state.codeSendCountdown > 0 ? `${state.codeSendCountdown}秒后重试` : '获取验证码' }}
                            </button>
                        </div>
                        <p v-if="errors.captcha" class="mt-1 text-sm text-red-600">{{ errors.captcha }}</p>
                    </div>

                    <button
                        type="submit"
                        :disabled="state.formLoading"
                        class="w-full py-3 px-4 bg-gradient-to-r from-indigo-600 to-purple-600 text-white font-medium rounded-lg hover:from-indigo-700 hover:to-purple-700 transition transform hover:scale-105 flex items-center justify-center"
                    >
                        <svg
                            v-if="state.formLoading"
                            class="animate-spin -ml-1 mr-2 h-5 w-5 text-white"
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                        >
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path
                                class="opacity-75"
                                fill="currentColor"
                                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                            ></path>
                        </svg>
                        立即注册
                    </button>
                    <!-- 社交登录 -->
                    <div class="mt-8">
                        <div class="relative">
                            <div class="absolute inset-0 flex items-center">
                                <div class="w-full border-t border-gray-300"></div>
                            </div>
                            <div class="relative flex justify-center text-sm">
                                <span class="px-2 bg-white text-gray-500">其他登录方式</span>
                            </div>
                        </div>

                        <div class="flex justify-center gap-4 mt-6">
                            <button
                                class="w-10 h-10 rounded-full bg-green-500 text-white flex items-center justify-center hover:bg-green-600 transition"
                            >
                                <i class="fa fa-weixin"></i>
                            </button>
                            <button
                                class="w-10 h-10 rounded-full bg-blue-500 text-white flex items-center justify-center hover:bg-blue-600 transition"
                            >
                                <img src="~assets/image/alipay.png" class="w-10" />
                            </button>
                            <button class="w-10 h-10 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transition">
                                <i class="fa fa-weibo"></i>
                            </button>
                        </div>
                    </div>
                </form>
                <!-- 第三方登录 -->

                <div class="mt-6 text-center text-sm text-gray-600">
                    已有账号？<router-link to="/login" class="text-indigo-600 hover:text-indigo-800">立即登录</router-link>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, onUnmounted, ref } from 'vue'
import { sendEms, sendSms } from '/@/api/common'
import { uuid } from '/@/utils/random'
import { checkIn, retrievePassword } from '/@/api/frontend/user/index'
import { useUserInfo } from '/@/stores/userInfo'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import clickCaptcha from '/@/components/clickCaptcha'
let timer: number

const route = useRoute()
const router = useRouter()
const userInfo = useUserInfo()

interface State {
    form: {
        tab: 'login' | 'register'
        email: string
        mobile: string
        username: string
        password: string
        captcha: string
        keep: boolean
        captchaId: string
        captchaInfo: string
        registerType: 'email' | 'mobile'
    }
    formLoading: boolean
    sendCaptchaLoading: boolean
    userLoginCaptchaSwitch: boolean
    accountVerificationType: string[]
    codeSendCountdown: number
    to: string
}
// 需要先定义errors对象
const errors = reactive({
    username: '',
    password: '',
    mobile: '',
    email: '',
    captcha: '',
})

const state: State = reactive({
    form: {
        tab: 'register',
        email: '',
        mobile: '',
        username: '',
        password: '',
        captcha: '',
        keep: false,
        captchaId: uuid(),
        captchaInfo: '',
        registerType: 'email',
    },
    formLoading: false,
    userLoginCaptchaSwitch: true,
    sendCaptchaLoading: false,
    accountVerificationType: [],
    codeSendCountdown: 0,
    to: route.query.to as string,
})
const handleSubmit = () => {
    if (!validateForm()) {
        return
    }
    state.formLoading = true
    /**
     * 调用此函数，自动调起点选文字验证码弹窗
     * 参数一：验证码ID
     * 参数二：验证成功后的回调函数
     * 参数三：额外的可配置项
     */
    clickCaptcha(state.form.captchaId, (captchaInfo) => {
        state.form.captchaInfo = captchaInfo
        checkIn('post', state.form)
            .then((res) => {
                state.formLoading = false
                userInfo.dataFill(res.data.userInfo)
                if (state.to) return (location.href = state.to)
                router.push({ path: 'user/login' })
            })
            .finally(() => {
                state.formLoading = false
            })
    })
}

const validateForm = () => {
    let isValid = true

    // 重置错误信息
    Object.keys(errors).forEach((key) => (errors[key] = ''))

    // 验证用户名
    if (!state.form.username.trim()) {
        errors.username = '请输入用户名'
        isValid = false
    } else if (state.form.username.length < 3) {
        errors.username = '用户名至少3个字符'
        isValid = false
    }

    // 验证密码
    if (!state.form.password) {
        errors.password = '请输入密码'
        isValid = false
    } else if (state.form.password.length < 6) {
        errors.password = '密码至少6个字符'
        isValid = false
    }

    // 验证手机号或邮箱
    if (state.form.registerType === 'mobile') {
        if (!state.form.mobile) {
            errors.mobile = '请输入手机号'
            isValid = false
        } else if (!/^1[3-9]\d{9}$/.test(state.form.mobile)) {
            errors.mobile = '请输入正确的手机号'
            isValid = false
        }
    }
    if (state.form.registerType === 'email') {
        if (!state.form.email) {
            errors.email = '请输入邮箱'
            isValid = false
        } else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(state.form.email)) {
            errors.email = '请输入正确的邮箱'
            isValid = false
        }
    }

    // 验证验证码
    if (!state.form.captcha) {
        errors.captcha = '请输入验证码'
        isValid = false
    }
    //else if (!/^\d{4}$/.test(state.form.captcha)) {
    //     errors.captcha = '验证码必须是4位数字'
    //     isValid = false
    // }

    return isValid
}
const sendCaptcha = () => {
    if (state.codeSendCountdown > 0) return
    // 根据注册类型验证手机或邮箱
    if (state.form.registerType === 'mobile') {
        if (!state.form.mobile || !/^1[3-9]\d{9}$/.test(state.form.mobile)) {
            errors.mobile = '请输入正确的手机号'
            return
        }
    }
    if (state.form.registerType === 'email') {
        if (!state.form.email || !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(state.form.email)) {
            errors.email = '请输入正确的邮箱'
            return
        }
    }

    clickCaptcha(state.form.captchaId, (captchaInfo: string) => {
        state.sendCaptchaLoading = true
        const func = state.form.registerType == 'email' ? sendEms : sendSms
        func(state.form[state.form.registerType], 'user_register', {
            captchaInfo,
            captchaId: state.form.captchaId,
        })
            .then((res) => {
                if (res.code == 1) startTiming(60)
            })
            .finally(() => {
                state.sendCaptchaLoading = false
            })
    })
}
const startTiming = (seconds: number) => {
    state.codeSendCountdown = seconds
    timer = window.setInterval(() => {
        state.codeSendCountdown--
        if (state.codeSendCountdown <= 0) {
            endTiming()
        }
    }, 1000)
}
const endTiming = () => {
    state.codeSendCountdown = 0
    clearInterval(timer)
}
</script>

<style scoped>
/* 添加一些动画效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.fade-in {
    animation: fadeIn 0.5s ease-out forwards;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .bg-opacity-90 {
        background-color: rgba(254, 251, 252);
    }
}
.bg-blue-500 {
    --tw-bg-opacity: 1;
    background-color: rgb(6 169 237 / 97%);
}
</style>
